package cn.edu.cqvie.netty.socket.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.UUID;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyServerHandler extends SimpleChannelInboundHandler<String> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // ctx 上下文
        // msg 数据内容
        System.out.println(ctx.channel().remoteAddress() + "," + msg);

        ctx.channel().writeAndFlush("from server: " + UUID.randomUUID());

        ctx.writeAndFlush("from server: " + UUID.randomUUID());

//        ExecutorService executor = Executors.newCachedThreadPool();
//        executor.submit(()-> {
//
//        });
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush("来自服务端的问候！");
    }

    /**
     * 出现异常
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
